// pages/order/order/details.js
import {
  find,
  cancel,
  received,
  reminder,
  payment,
  del,
  paymentFirst,
} from '../../../api/order';
import {
  submit,
  query
} from '../../../api/payment';
import {
  buyForOrder
} from '../../../api/cart';
import {find as findProduct} from "../../../api/product"
const util = require('../../../utils/util.js')
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderQueryType: false,
    logisticsForm: [],
    id: '',
    orderForm: null,
    shopVo: null,
    payments: [],
    discountTotal: 0,
    sn: '',
    orderType:'待付款',
    findForm:[],
    shopId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.data.id = options.id
  },

  onShow: function () {
    this.findClick(this.data.id)
  },
  orderQueryClick() {
    this.data.orderQueryType = !this.data.orderQueryType
    this.setData({
      orderQueryType: this.data.orderQueryType
    })
  },
  refundClick() {
    wx.navigateTo({
      url: '/pages/order/refund/details?id=' + this.data.orderForm.id,
    })
  },
  // 订单详情
  findClick(data) {
    var _this = this
    console.log(data)
    find(data).then(
      res => {
        if (res.type == 'success') {
          console.log('商品详情')
          console.log(res)
          _this.data.orderForm = res.data.order
          _this.data.shopVo = res.data.shopVo
          _this.data.shopId = res.data.shopVo
          res.data.orderLog.forEach(item=>{
            item.createDate=util.datetimeFormat( item.createDate)
          })
          _this.data.logisticsForm = res.data.orderLog
          _this.data.payments = res.data.payments
          _this.data.discountTotal = (Number(res.data.order.discount) + Number(res.data.order.couponDiscount)).toFixed(2)
          if(_this.data.orderForm.paymentStatus ==0 && _this.data.orderForm.shippingStatus == 0 && _this.data.orderForm.orderStatus ==0){
            _this.data.orderType = '待付款'
          }else if(_this.data.orderForm.paymentStatus ==1 && _this.data.orderForm.shippingStatus == 0 && _this.data.orderForm.orderStatus ==1){
            _this.data.orderType = '已付款'
          }else if(_this.data.orderForm.paymentStatus ==1 && _this.data.orderForm.shippingStatus == 1 && _this.data.orderForm.orderStatus ==1){
            _this.data.orderType = '已付款'
          }else if(_this.data.orderForm.paymentStatus ==1 && _this.data.orderForm.shippingStatus == 1 && _this.data.orderForm.orderStatus ==2){
            _this.data.orderType = '待评价'
          }else{
            _this.data.orderType = '待处理'
          }
          _this.data.orderForm.createDate = util.datetimeFormat(_this.data.orderForm.createDate)
          if(_this.data.orderForm.orderType == 1){
            var date = util.datetime(_this.data.orderForm.estimateDate)
            console.log(util.filterTime(_this.data.orderForm.estimateDate))
            if(util.filterTime(_this.data.orderForm.estimateDate) == "12:00:00"){
              _this.data.orderForm.estimateDate = date + ' ' + '午餐'
            }else if(util.filterTime(_this.data.orderForm.estimateDate) == "18:00:00"){
              _this.data.orderForm.estimateDate = date + ' ' + '晚餐'
            }else{
              _this.data.orderForm.estimateDate = util.datetimeFormat(_this.data.orderForm.estimateDate)
            }
          }else{
            _this.data.orderForm.estimateDate = util.datetimeFormat(_this.data.orderForm.estimateDate)
          }
          _this.findProductClick(res.data.order.itemList[0].productId)
          // _this.data.orderForm.orderType = 1
          _this.setData({
            orderForm: _this.data.orderForm,
            shopVo: _this.data.shopVo,
            logisticsForm: _this.data.logisticsForm,
            payments: _this.data.payments,
            discountTotal: _this.data.discountTotal,
            orderType:_this.data.orderType
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  // 付款按钮
  paymentClick(data) { // 付款
    var _this = this
    wx.showLoading({
      title: '加载中...',
      mask:true
    })
    if(_this.data.orderForm.orderType == 1){
      paymentFirst(data.currentTarget.dataset.id).then(res => {
        if (res.type == 'success') {
          console.log(res)
          _this.submitClick(res)
        } else {
          wx.hideLoading()
          wx.showToast({
            icon: "none",
            title: '支付失败',
          })
        }
      }).catch(error => {
        wx.hideLoading()
        wx.showToast({
          icon: "none",
          title: error.content,
        })
      })
    }else{
      payment(data.currentTarget.dataset.id).then(res => {
        if (res.type == 'success') {
          console.log(res)
          _this.submitClick(res)
        } else {
          wx.hideLoading()
          wx.showToast({
            icon: "none",
            title: '支付失败',
          })
        }
      }).catch(error => {
        wx.hideLoading()
        wx.showToast({
          icon: "none",
          title: error.content,
        })
      })
    }
  },
  submitClick(data) {
    var _this = this
    console.log(data)
    _this.data.sn = data.data.sn
    submit({
      paymentPluginId: 'weixinMiniPayPlugin',
      sn: data.data.sn
    }).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res.type == 'success') {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (red) {
            setTimeout(function(){
              _this.queryClick()
            }, 100);
          },
          'fail': function (red) {
            console.log(red);
          }
        })
      } else {
        wx.showToast({
          icon: "none",
          title: '支付失败',
        })
      }
    }).catch(error => {
      wx.hideLoading()
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },
  queryClick() {
    var _this = this
    query({
      sn: _this.data.sn
    }).then(res => {
      console.log(res)
      if (res.type == 'success') {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1500,
          success: function () {
            setTimeout(function () {
              wx.navigateBack({})
            }, 1500)
          }
        })
      } else {
        wx.navigateBack({})
      }
    }).catch(error => {

    })
  },
  // 删除订单
  delClick() {
    var _this = this
    wx.showModal({
      title: '提示',
      content: '是否确认取消！',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中...',
            mask:true
          })
          cancel(_this.data.id).then(
            res => {
              wx.hideLoading()
              if (res.type == 'success') {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          ).catch(error => {
            wx.hideLoading()
            console.log(error)
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //再次购买
  again() { // 再次购买
    // debugger
    if(this.data.shopVo.status&&this.data.shopVo.status != 1){
      wx.showToast({
        icon: 'none',
        title: '商户已关闭未开放',
      })
      return
    }
    var _this = this
    console.log(this.data.orderForm)
    var product = this.data.orderForm.itemList[0]
    let data = {}
    data.orderId = product.orderId
    data.uuid = app.globalData.uuid
    wx.showLoading({
      title: '加载中...',
      mask:true
    })
    buyForOrder(data).then(
      res => {
        wx.hideLoading()
        if (res.type == 'success') {
          if(_this.data.orderForm.orderType == 1){
            wx.navigateTo({
              url: '/pages/cook/KBOrderDetail/KBOrderDetail?shopId='+_this.data.shopVo.id,
            })
          }else{
            wx.navigateTo({
              url: '/pages/shop/settlement/index?shopId='+_this.data.shopVo.id,
            })
          }   
        }
      }
    ).catch(error => {
      wx.hideLoading()
      wx.showToast({
        title: '服务器开小差了，请重新点击购买',
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 退款
  refundsclick() {
    wx.navigateTo({
      url: '/pages/order/refund/index?id=' + this.data.orderForm.id,
    })
  },
  //评价
  evaluateClick(){
    wx.navigateTo({
      url: '/pages/order/evaluate/evaluate?id=' + this.data.orderForm.id,
    })
  },
  // 回首页
  indexClick(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  // 确认收货
  receivedClick() {
    var _this = this
    wx.showModal({
      title: '提示',
      content: '是否确认收货！',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中',
            mask:true
          })
          received(_this.data.id).then(
            res => {
              wx.hideLoading()
              if (res.type == 'success') {
                wx.showToast({
                  title: res.content,
                })
                _this.findClick(_this.data.id)
              }
            }
          ).catch(error => {
            wx.hideLoading()
            console.log(error)
          })
        } else if (res.cancel) {
          wx.hideLoading()
          console.log('用户点击取消')
        }
      }
    })
  },
  // 尾款
  balanceClick(){
    var _this = this
    payment(this.data.orderForm.id).then(res => {
      if (res.type == 'success') {
        console.log(res)
        _this.submitClick(res)
      } else {
        wx.hideLoading()
        wx.showToast({
          icon: "none",
          title: '支付失败',
        })
      }
    }).catch(error => {
      wx.hideLoading()
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },
  findProductClick(id){
    var _this = this
    findProduct(id).then(res=>{
      console.log(res)
      _this.data.findForm = res.data.meta.props
      _this.setData({
        findForm:_this.data.findForm
      })
      console.log(_this.data.findForm)
    })
  },
  toShop(){
    wx.navigateTo({
      url: `/pages/shop/shopDetail/index?shopId=${this.data.shopVo.id}`,
    })
}
})
